#include "timer.h"
#include "led.h"
#include "digital_tube.h"
#include "rule.h"
extern DigitalTube_TypeDef system_time_tube;
SystemTime_TypeDef  system_time;
TrafficTime_TypeDef  traffic_time;

void SystemTime_Excute(void *self)
{
	SystemTime_TypeDef *tmp = (SystemTime_TypeDef *)self;
	
	tmp->milisecond += 1;
	
	if( tmp->milisecond >= 1000 )
	{
		tmp->milisecond = 0;
		
		tmp->second += 1;
		if( tmp->second >= 60 )
		{
			tmp->second = 0;
			tmp->minute += 1;
			if( tmp->minute >= 60 )
			{
				tmp->hour += 1;
				if( tmp->hour >= 24 )
				{
					tmp->hour = 0;
				}
			}
		}
		
		system_time_tube.tube_character[0] = tmp->second%10 + 0x30;
		system_time_tube.tube_character[1] = tmp->second/10 + 0x30;
		system_time_tube.tube_character[2] = '-';
		system_time_tube.tube_character[3] = tmp->minute%10 + 0x30;
		system_time_tube.tube_character[4] = tmp->minute/10 + 0x30;
		system_time_tube.tube_character[5] = '-';
		system_time_tube.tube_character[6] = tmp->hour%10 + 0x30;
		system_time_tube.tube_character[7] = tmp->hour/10 + 0x30;		
		
	}
}




void TrafficTime_Excute(void *self)
{
	TrafficTime_TypeDef *tmp = (TrafficTime_TypeDef*)self;

	tmp->milisecond += 1;
	Traffic_Rule();
	
	if( tmp->milisecond >= 1000 )		
	{
		tmp->milisecond = 0;
		
		tmp->rest_cnt -= 1;	
	
		if( tmp->rest_cnt == 0 )
		{				
			if( tmp->status == RED_LIGHT )
			{
				tmp->rest_cnt = tmp->green_period;
				
				tmp->status = GREEN_LIGHT;
			}
			else if( tmp->status == GREEN_LIGHT )
			{
				tmp->rest_cnt = tmp->red_period;
			
				tmp->status = RED_LIGHT;		
			}	
		}
	}
}	





void TimeInit(void)
{
	system_time.hour = 0;
	system_time.minute = 0;
	system_time.second = 0;
	system_time.update = SystemTime_Excute;
	
	
	traffic_time.red_period = 60;
	traffic_time.green_period = 60;
	traffic_time.rest_cnt = 60;	
	traffic_time.status = RED_LIGHT;
	traffic_time.update = TrafficTime_Excute;
	
}



void Timer_Task(uint8_t excute_period) 
{
	while(excute_period--)
	{
		system_time.update( &system_time );
		traffic_time.update( &traffic_time );
	}
}



